
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../common/common_utils.dart';
import '../../model/net_resp_entity.dart';


class ResponseInterceptor extends Interceptor {
  RequestOptions? requestOptions;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    requestOptions = options;
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    try {
      NetRespEntity respEntity = NetRespEntity.fromJson(response.data);
      if (respEntity.code >= 200 && respEntity.code < 400) {
        handler.next(response);
      } else if(respEntity.code == 100){
        EasyLoading.showToast('用户登录过期!');
        CommonUtils.logout();
      } else if(respEntity.code == 400){
        EasyLoading.showToast(respEntity.message);
      } else{
        EasyLoading.showToast("错误: code--> ${respEntity.code}, message --> ${respEntity.message}");
      }
    } catch (e) {
      handler.reject(
          DioError(requestOptions: requestOptions!, message: "服务器错误：$e"));
      EasyLoading.showToast('服务器异常，请稍后重试!');
    }
  }

  ResponseInterceptor();
}